//
//  SETagsCollectionViewFlowLayout.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/15.
//

import UIKit

extension UICollectionViewLayoutAttributes {
    func leftAlignFrameWithSectionInset(_ sectionInset: UIEdgeInsets){
        frame.origin.x = sectionInset.left
    }
}

class SETagsCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    /// 所有cell和view的布局属性
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let originalAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
        
        var updatedAttributes = originalAttributes
        
        for attributes in updatedAttributes {
            guard attributes.representedElementKind == nil else { continue }
            guard let index = updatedAttributes.firstIndex(of: attributes) else { continue }
            if let attr = layoutAttributesForItem(at: attributes.indexPath) {
                updatedAttributes[index] = attr
            }
        }
        return updatedAttributes
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        guard let collectionView = collectionView,
              let currentItemAttrs = super.layoutAttributesForItem(at: indexPath) else { return nil }
        
        let currentItemAttributes = currentItemAttrs.copy() as! UICollectionViewLayoutAttributes
        
        let isFirstItemInSection = indexPath.item == 0
        let layoutWidth = collectionView.frame.width - sectionInset.left - sectionInset.right
        
        if isFirstItemInSection {
            currentItemAttributes.leftAlignFrameWithSectionInset(sectionInset)
            return currentItemAttributes
        }
        
        let previousIndexPath = IndexPath(row: indexPath.item - 1, section: indexPath.section)
        let previousFrame = layoutAttributesForItem(at: previousIndexPath)?.frame ?? .zero
        let previousFrameRight = previousFrame.minX + previousFrame.width
        
        let currentFrame = currentItemAttributes.frame
        let strecthedCurrentFrame = CGRect(x: sectionInset.left,
                                           y: currentFrame.minY,
                                           width: layoutWidth,
                                           height: currentFrame.height)
        
        let isFirstItemInRow = !previousFrame.intersects(strecthedCurrentFrame)
        
        if isFirstItemInRow {
            // make sure the first item on a line is left aligned
            currentItemAttributes.leftAlignFrameWithSectionInset(sectionInset)
            return currentItemAttributes
        }
        
        currentItemAttributes.frame.origin.x = previousFrameRight + minimumLineSpacing
        return currentItemAttributes
    }
}
